package com.xiashitech.apiservice.job;

import com.xiashitech.apiservice.job.base.XSQuartzJobBean;
import com.xiashitech.apiservice.service.IAgentSystemStatusService;
import com.xiashitech.apiservice.util.DateUtil;
import com.xiashitech.interfaces.agent.constants.AgentStatus;
import com.xiashitech.interfaces.agent.dto.SystemInfoDTO;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.ZoneId;

@Configuration
public class AgentStatusCheck {
    @DisallowConcurrentExecution
    class RecoverNotRun extends XSQuartzJobBean {

        //最大检测agent停止时间间隔为3分钟
        public static final long DOWNTIME = 3l;

        IAgentSystemStatusService statusServiceNameBean;

        public void setStatusServiceNameBean(IAgentSystemStatusService statusServiceNameBean) {
            this.statusServiceNameBean = statusServiceNameBean;
        }

        @Override
        protected void xsExecuteInternal(JobExecutionContext context) throws JobExecutionException {
            statusServiceNameBean.selectAllAgentStatus().stream().forEach(systemInfoDTO -> {
                SystemInfoDTO systemInfoDTOCache = statusServiceNameBean.selectAgentStatusByCache(systemInfoDTO.getId(), systemInfoDTO.getMicroServiceId());
                if(systemInfoDTOCache != null && AgentStatus.RUNNING.getValue() == systemInfoDTOCache.getAgentStatus() && systemInfoDTOCache.getAgentStatusHeartBeat() != null) {
                    LocalDateTime heartBeatDate = LocalDateTime.ofInstant(systemInfoDTOCache.getAgentStatusHeartBeat().toInstant(),ZoneId.systemDefault());
                    LocalDateTime nowDateTime = LocalDateTime.now();
                    long secondsBetween = DateUtil.minutesBetween(heartBeatDate, nowDateTime);
                    if(secondsBetween > DOWNTIME) {
                        statusServiceNameBean.updateAgentStatusByCache(systemInfoDTOCache.getId(),systemInfoDTOCache.getMicroServiceId(),AgentStatus.NOT_RUN.getValue(),Boolean.FALSE);
                    }
                }
            });
        }
    }
    @Bean("recoverNotRunJobDetail")
    public JobDetail downloadDetail() {
        return JobBuilder.newJob(RecoverNotRun.class)
                .usingJobData("statusServiceName","agentSystemStatusService")
                .storeDurably()
                .build();
    }
    @Bean("recoverNotRunTrigger")
    @Autowired
    @Qualifier("recoverNotRunJobDetail")
    public Trigger downloadTrigger(JobDetail jobDetail) {
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withSchedule(CronScheduleBuilder.cronSchedule("0 */1 * * * ? *"))
                .build();
    }
}
